﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IveelySE.Common
{
    /// <summary>
    /// 进度条显示
    /// </summary>
    public class ProcessBar
    {
        /// <summary>
        /// 背景色
        /// </summary>
        private ConsoleColor _colorBack = Console.BackgroundColor;
        /// <summary>
        /// 前景色
        /// </summary>
        private ConsoleColor _colorFore = Console.ForegroundColor;
        /// <summary>
        /// 显示标题
        /// </summary>
        private string _title;
        /// <summary>
        /// 总长度
        /// </summary>
        private int _length;
        /// <summary>
        /// 开始所在的控制台行
        /// </summary>
        private int _startLine;
        /// <summary>
        /// 每个单元长度
        /// </summary>
        private double _unit;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="length">长度</param>
        public ProcessBar(string title, int length)
        {
            this._title = title;
            this._length = length;
            this._unit = 50.0 / this._length;
        }

        /// <summary>
        /// 初始化操作
        /// </summary>
        public void Init()
        {
            _startLine = Console.CursorTop + 1;
            //标识信息            
            Console.WriteLine(this._title);
            //进度条背景
            Console.BackgroundColor = ConsoleColor.DarkCyan;
            for (int i = 0; ++i <= 50; )
            {
                Console.Write(" ");
            }
            Console.WriteLine(" ");
            Console.BackgroundColor = _colorBack;
            //最初进度         
            Console.WriteLine("0%");

        }

        /// <summary>
        /// 设置当前所在
        /// </summary>
        /// <param name="i"></param>
        public void Current(int i)
        {
            int step = int.Parse(Math.Round(i * this._unit).ToString());
            //绘制进度条进度                 
            Console.BackgroundColor = ConsoleColor.Yellow;//设置进度条颜色                 
            Console.SetCursorPosition(step, _startLine);//设置光标位置,参数为第几列和第几行                 
            Console.Write(" ");//移动进度条                 
            Console.BackgroundColor = _colorBack;//恢复输出颜色                 
            //更新进度百分比,原理同上.                 
            Console.ForegroundColor = ConsoleColor.Green;
            Console.SetCursorPosition(0, _startLine + 1);
            Console.Write("完成:{0}%", step * 2);
            Console.ForegroundColor = _colorFore;
        }

        /// <summary>
        /// 运行完记得清楚，以还原控制台
        /// </summary>
        public void Clean()
        {
            Console.SetCursorPosition(0, _startLine + 2);
        }
    }
}
